import styles from './index.module.scss'
import { useState,useRef } from 'react'
import{http,setToken} from "@/utils"
import * as Yup from 'yup'
import{Toast} from"antd-mobile"
import { useFormik } from 'formik'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
// let timeId = -1
const Login = ({history}) => {
  const [time, setTime] = useState(0)
  const timerIdref=useRef(-1)
  const formik = useFormik({
    initialValues: {
      mobile: '',
      code: '',
    },
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('手机号为必填项 ')
        .matches(/^1[3-9]\d{9}$/, '手机号码格式不正确'),
      code: Yup.string()
        .required('验证码为必填项')
        .matches(/^\d{6}$/, '验证码不正确'),
    }),
    // 登录成功后跳转页面
    onSubmit: async values => {
      try{const res=await http.post(
        '/authorizations',values
      )
      if(res.data.message.toLowerCase()==="ok"){
        Toast.info("登录成功",1,()=>{
          // console.log("弹窗关闭了");
          clearInterval(timerIdref.current)
          history.push("/home")
          // localStorage.setItem("geek-app-87",JSON.stringify(res.data.data))
          setToken(res.data.data)
        })
      }
    }catch(e){
      Toast.info(e.response.data.message,2)
    }
    }
  })
  const getCode = async () => {
    const { mobile } = formik.values
    if (!/^1[3-9]\d{9}$/.test(mobile)) return
    setTime(59)
    clearInterval(timerIdref.current)
    timerIdref.current= setInterval(() => {
      setTime(time => {
        if (time === 1) {
          clearInterval(timerIdref.current)
        }
        return time - 1
      })
    }, 1000)
    try {
      await http.get(`/sms/codes/${mobile}`)
    } catch (e) {}
  }
  const {
    handleSubmit,
    handleChange,
    handleBlur,
    values: { mobile, code },
    touched,
    errors,
    isValid
  } = formik

  // const [mobile,setMobile]=useState("")
  // const[code,setCode]=useState("")
  // const onSubmit=e=>{
  //     e.preventDefault()
  // }
  // Object.keys(touched) 用来获取对象中所有的键，结果为数组
  // 如果得到的数组长度为 0，说明对象中没有属性，也就是 两个表单元素
  // 都没有获得过焦点，也就是第一次点击
  const isFirst=Object.keys(touched).length===0
  return (
    <div className={styles.root}>
          {/* 导航栏组件 */}
          <NavBar onClick={() => history.go(-1)} />
      <p className="title">账号登录</p>
      <div className="login-wrap">
        <form onSubmit={handleSubmit}>
          <div className="form-item">
            <Input
              name="mobile"
              type="text"
              placeholder="请输入手机号"
              value={mobile}
              onChange={handleChange}
              onBlur={handleBlur}
            />
            <div className="error">
              {touched.mobile && formik.errors.mobile ? <div>{errors.mobile}</div> : null}
            </div>
          </div>
          <div className="form-item">
            <Input
            extra={time <= 0 ? '发送验证码' : `${time}s`}
              name="code"
              type="text"
              placeholder="请输入验证码"
              onBlur={handleBlur}
              value={code}
              onChange={handleChange}
              onExtraCliick={getCode}
              className="red"
            />
            {/* <span onClick={getCode} className="code-text">
              {time <= 0 ? '发送验证码' : `${time}s`}
            </span> */}
            <div className="error">
              {touched.code && errors.code ? <div>{errors.code}</div> : null}
            </div>
          </div>
          <div className="form-item">
            <button type="submit"
            disabled={isFirst||!isValid}
            className={isFirst?"":isValid?"active":""}
            >登录</button>
          </div>
        </form>
      </div>
    </div>
  )
}
export default Login
